#include "lua_str.h"
#include "lua_utils.h"
#include <string>
#include "Win32Utils/CPathUtils.h"
#include "Win32Utils/CStrUtils.h"

static luaL_Reg lib_functions[] =
{
    { "is_utf8", &lua_str::is_utf8},
    { "a_to_u8", &lua_str::ansi_to_utf8},
    { "u8_to_a", &lua_str::utf8_to_ansi},
    { NULL, NULL}
};

void lua_str::initialize(lua_State* L, const char* lib_name)
{
    lua_newtable(L);

    luaL_Reg* fun_info = lib_functions;
    while (fun_info->func)
    {
        lua_pushcfunction(L, fun_info->func);
        lua_setfield(L, -2, fun_info->name);
        fun_info++;
    }
    lua_setfield(L, -2, lib_name);
}

void lua_str::uninitialize()
{

}

int lua_str::is_utf8(lua_State* L)
{
    int top = lua_gettop(L);
    std::string str_ata;

    if (top >= 1 && lua_isstring(L, -1))
    {
        str_ata = lua_tostring(L, -1);
    }

    int count = CStrUtils::GetUtf8CharacterCount(str_ata);
    lua_pushboolean(L, count >= 0);

    return 1;
}

int lua_str::ansi_to_utf8(lua_State* L)
{
    int top = lua_gettop(L);
    std::string str_ata;

    if (top >= 1 && lua_isstring(L, -1))
    {
        str_ata = lua_tostring(L, -1);
    }

    std::string str_result = CStrUtils::AStrToU8Str(str_ata);
    lua_pushstring(L, str_result.c_str());

    return 1;
}

int lua_str::utf8_to_ansi(lua_State* L)
{
    int top = lua_gettop(L);
    std::string str_ata;

    if (top >= 1 && lua_isstring(L, -1))
    {
        str_ata = lua_tostring(L, -1);
    }

    std::string str_result = CStrUtils::U8StrToAStr(str_ata);
    lua_pushstring(L, str_result.c_str());

    return 1;
}
